import { _decorator, EventTouch, Node, v2, v3, Vec3 } from 'cc';
import { Drawer } from '../../../src/ui/structure/drawer';
import { Tile } from '../../../src/ui/structure/tile';
const { ccclass, property } = _decorator;

@ccclass('GDrawerStash')
export class GDrawerStash extends Drawer {

	protected onLoad(){
		super.onLoad();
	}

	protected start(){
		this.left_board = -this.uitrans.width * this.uitrans.anchorX;

		this.tile_size = Tile.calculateViewSize(this.uitrans.width, this.uitrans.height).box;
		this.capacity = Math.floor(this.uitrans.width / this.tile_size.width);
		this.padding_x = (this.uitrans.width - this.tile_size.width * this.capacity) / (this.capacity + 1);
		this.tween_speed = Math.max(this.tile_size.width, this.tile_size.height) / 0.1;

		this.node.on(Node.EventType.TOUCH_END, this.touchEnd, this);
	}

	private touch = {
		location: v2(),
		position: v3(),
		world_position: v3(),
	}

	private touchEnd(event: EventTouch){
		event.getUILocation(this.touch.location);
		this.touch.world_position.set(this.touch.location.x, this.touch.location.y, 0);
		this.uitrans.convertToNodeSpaceAR(this.touch.world_position, this.touch.position);

		let select_item: typeof this.record_list[number];
		let distance = v3();
		for(let record of this.record_list.filter(r=>!this.adding_tile.find(el=>el.token==r.token))){
			Vec3.subtract(distance, record.tile.node.position, this.touch.position);
			if([distance.x/this.tile_size.width, distance.y/this.tile_size.height].every(v=>Math.abs(v)<=0.5)){
				select_item = record;
				break;
			}
		}
		distance = null;

		if(select_item){
			GDrawerStash.select_call_list.forEach(call=>call(select_item));
		}
	}

	private static select_call_list: ((record: InstanceType<typeof GDrawerStash>['record_list'][number])=>any)[] = [];
	public static onSelectRecord(call: (record: InstanceType<typeof GDrawerStash>['record_list'][number])=>any){
		this.select_call_list.push(call);
	};

	public removeRecord(tile: Tile){
		let record = this.removeRecordByTile(tile);
		if(record) this.refresh();
	}
}

